<?php

include "validate.php";
include "db_con.php";

if (isset($_POST["sensor"]))
	$name = $_POST["sensor"];
else
	$name = "";
if (isset($_POST["file"]))
	$file = $_POST["file"];
else
	$file = "";
if (isset($_POST["type"]))
	$type = $_POST["type"];
else
	$type = "";

if (strlen($name) > 0 && strlen($file) > 0 && strlen($type) > 0)
{
	$query = "	SELECT sensor_id AS ID
			FROM sensor
			WHERE name = '" . $name . "';";

	$result = mysql_query($query);

	if ($row = mysql_fetch_array($result))
	{
		$ID = $row['ID'];
		
		$query = "	SELECT account_id AS ID
				FROM login
				WHERE user_name = '" . $_SESSION['username'] . "';";
		
		$result = mysql_query($query);

		if ($row = mysql_fetch_array($result))
		{
			$query = "	INSERT INTO records (records_id, sensor_id, account_id)
					SELECT NULL,
					" . $ID . ", 
					" . $row['ID'] . ";";

			mysql_query($query);

			$query = "	SELECT MAX(records_id) AS record
					FROM records
					WHERE sensor_id = " . $ID . ";";

			$tmpResult = mysql_query($query);

			$tmpRow = mysql_fetch_array($tmpResult);

			$record_id = $tmpRow['record'];

			$query = "	SELECT MAX(submission_id) AS NUM
					FROM new_submissions;";

			$result = mysql_query($query);
			
			if ($row = mysql_fetch_array($result))
				$new_id_num = $row['NUM'] + 1;
			else
				$new_id_num = 1;

			$query = "	INSERT INTO new_submissions (database_name, records_id)
					SELECT 'dionaea_" . $new_id_num . "', '" . $record_id . "';";
			mysql_query($query);

			exec("./create_dionaea.sh uploads/" . $file . " " . $new_id_num . " > /dev/null 2>&1 &");

			$_SESSION['message'] = "Uploading...";
			header("Location:sensor_upload.php");
		}
		else
		{
			$_SESSION['message'] = "Unknown User";
			header("Location:sensor_upload.php");
		}
	}
	else
	{
		$_SESSION['message'] = "Unknown Sensor";
		header("Location:sensor_upload.php");
	}
}
else
{
	$_SESSION['message'] = "Not a valid selection";
	header("Location:sensor_upload.php");
}
?>
